package com.shijie.newvideo.utils;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

/**
 * 自运设置宽高
 *
 * @author 刘汝寿
 * @date 2018/5/4
 */
public class AutoResizeRelativeLayout extends RelativeLayout {
    private AutoResizeHeightHelper mAutoResizeHeightHelper;

    public AutoResizeRelativeLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public AutoResizeRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public AutoResizeRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        mAutoResizeHeightHelper = new AutoResizeHeightHelper(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mAutoResizeHeightHelper.getWhRate() != 0) {
            int w = getMeasuredWidth();
            int h = ViewUtils.getAutoResizeHeight(this, w, mAutoResizeHeightHelper.getWhRate());
            //noinspection ConstantConditions 因为可能复制到别的地方使用，所以仍然作判断
            if (this instanceof ViewGroup) {
                //view group 高度mode设置为EXACTLY
                super.onMeasure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.getMode(widthMeasureSpec)), MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY));
            } else {
                //view
                setMeasuredDimension(w, h);
            }
        }
    }

    public AutoResizeHeightHelper getAutoResizeHeightHelper() {
        return mAutoResizeHeightHelper;
    }
}
